package cn.liangjintang.foldbrowerbundle;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import cn.liangjintang.foldbrowerbundle.R;

/**
 * 文件夹对话框的主要View构造器,可以构造文件对话框的View部分,不包括确定,取消等按钮
 */
public class FoldViewBuilder {
    List<File> disk = null;
    TextView tv;
    ListView lv;
    Context ct;
    FileListAdapter fileListAdapter;
    public View foldView;
    public File selectedFileDir = null;

    public FoldViewBuilder(Context context) {
        ct = context;
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        foldView = layoutInflater.inflate(R.layout.foldbrowerbundle_foldview,
                null);
        tv = (TextView) foldView.findViewById(R.id.dir_tv);
        lv = (ListView) foldView.findViewById(R.id.dir_lv);
        fileListAdapter = new FileListAdapter(ct);
        lv.setAdapter(fileListAdapter);
        lv.setOnItemClickListener(onItemClickListener);
        foldView.findViewById(R.id.dir_iv).setOnClickListener(diskButtonOnClickListener);
    }

    private final void showDisk() {
        if (disk == null) {
            disk=new ArrayList<>();
            StorageList sl = new StorageList(ct);
            disk.add(new File("/"));
            String[] files = sl.getVolumePaths();
            for (String file : files) {
                disk.add(new File(file));
            }
        }
        fileListAdapter.setData(disk);
        setSelectedFileDir(disk.get(0));
    }

    /**
     * @param dir 设置对话框的根目录
     */
    public final void setDataAndShow(File dir) {
        List<File> fileList = new ArrayList<File>();
        File[] files = dir.listFiles();
        fileList.add(dir.getParentFile());
        for (File f : files) {
            if (f.isDirectory())
                fileList.add(f);
        }
        Collections.sort(fileList, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                int x=o1.getName().compareToIgnoreCase(o2.getName());
                return x!=0?x:o1.getName().compareTo(o2.getName());
            }
        });
        fileListAdapter.setData(fileList);
        setSelectedFileDir(dir);
    }

    private void setSelectedFileDir(File selectedFileDir) {
        this.selectedFileDir = selectedFileDir;
        tv.setText(selectedFileDir.getPath());
    }

    /**
     * 可以在当前目录新建一个文件夹
     */
    public final boolean newDir(String name) {
        if (name == null)
            return false;
        File file = new File(selectedFileDir, name);
        boolean b = file.mkdir();
        if (b) {
            setDataAndShow(file);
        }
        return b;
    }
    View.OnClickListener diskButtonOnClickListener=new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDisk();
        }
    };
    OnItemClickListener onItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            File file = fileListAdapter.files.get(arg2);
            if (file != null && file.canRead())
                setDataAndShow(file);
        }
    };

    public class StorageList {
        private StorageManager mStorageManager;
        private Method mMethodGetPaths;
        /**
         * total space
         */
        public static final int TOTALSPACE = 0;
        /**
         * free space
         */
        public static final int FREESPACE = 1;

        public StorageList(Context context) {
            if (context != null) {
                mStorageManager = (StorageManager) context
                        .getSystemService(Activity.STORAGE_SERVICE);

                try {
                    mMethodGetPaths = mStorageManager.getClass().getMethod(
                            "getVolumePaths");
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
        }

        public String[] getVolumePathsFor14() {
            String[] paths = null;
            try {
                paths = (String[]) mMethodGetPaths.invoke(mStorageManager);
            } catch (IllegalArgumentException e) {

            } catch (IllegalAccessException e) {

            } catch (InvocationTargetException e) {

            } catch (Exception e) {

            }
            return paths;
        }

        public String[] getVolumePaths() {
            if (android.os.Build.VERSION.SDK_INT >= 14) {
                return getVolumePathsFor14();
            } else if (Environment.MEDIA_MOUNTED.equals(Environment
                    .getExternalStorageState())) {
                return new String[]{Environment.getExternalStorageDirectory()
                        .getAbsolutePath()};
            }
            return null;
        }

        /**
         * @param type, see {@link #TOTALSPACE}, or {@link #TOTALSPACE}.
         * @return
         */
        public String getBestVolumePaths(int type) {
            String[] vps = getVolumePaths();
            if (vps == null)
                return null;
            if (vps.length == 1)
                return vps[0];
            File file = new File(vps[0]);
            if (type == TOTALSPACE) {
                for (int i = 1; i < vps.length; i++) {
                    File file2 = new File(vps[i]);
                    if (file2.getTotalSpace() > file.getTotalSpace())
                        file = file2;
                }
            } else if (type == FREESPACE) {
                for (int i = 1; i < vps.length; i++) {
                    File file2 = new File(vps[i]);
                    if (file2.getFreeSpace() > file.getFreeSpace())
                        file = file2;
                }
            }
            return file.getAbsolutePath();
        }
    }
}
